package baduga.karo;
import baduga.client.Controler;
import baduga.client.Game_Cfg;
import baduga.client.Network_API__ClientThread;
import baduga.client.Player_Constans;
import baduga.core.*;

import java.awt.Color;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.UIManager;

import java.awt.Toolkit;

import javax.swing.JButton;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JFrame;




//Klasa klienta laczacego sie z serwerem na wybranym porcie.

/**
 * @author Karolina
 */
public class LoginScreen extends JFrame {

	private static final long serialVersionUID = 1L;
	
	private Controler contr;
	
	
	
    private JButton jButtonPlay;
    private JLabel jLabelAddressPort;
    private JLabel jLabelConnectionInfo;
    private JLabel jLabelNick;
    private JLabel jLabelSeparator;
    private JMenu jMenu;
    private JMenuBar jMenuBar1;
    private JMenu jMenuFile;
    private JMenuItem jMenuItemAbout;
    private JMenuItem jMenuItemExit;
    private JMenuItem jMenuItemHelp;
    private JTextField jTextFieldIP;
    private JTextField jTextFieldNick;
    private JTextField jTextFieldPort;
    private java.awt.Menu menu1;
    private java.awt.Menu menu2;
    private java.awt.Menu menu3;
    private java.awt.Menu menu4;
    private java.awt.Menu menu5;
    private java.awt.Menu menu6;
    private java.awt.MenuBar menuBar1;
    private java.awt.MenuBar menuBar2;
    private java.awt.MenuBar menuBar3;
	
	

	//tworzymy okienko aplikacji
	
    public LoginScreen() {
		setIconImage(Toolkit.getDefaultToolkit().getImage(LoginScreen.class.getResource("/baduga/karo/resources/icon.png")));
        initComponents();
    }
    
    
    
    
    public LoginScreen(Controler newContr)
    {
    	
    	this.contr = newContr;
    	

    	
    	
        try {
        UIManager.LookAndFeelInfo[] installedLookAndFeels=UIManager.getInstalledLookAndFeels();
            for (UIManager.LookAndFeelInfo installedLookAndFeel : installedLookAndFeels) {
                if ("Windows".equals(installedLookAndFeel.getName())) {
                    UIManager.setLookAndFeel(installedLookAndFeel.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
    	
        
        
        
        
		setIconImage(Toolkit.getDefaultToolkit().getImage(LoginScreen.class.getResource("/baduga/karo/resources/icon.png")));
        initComponents();
        
        
        
        this.setVisible(true);
        this.setLocationRelativeTo(null);                
        this.addWindowListener(new java.awt.event.WindowAdapter() {});

        //Przy wyjściu z aplikacji następuje rozłączenie z serwerem

        //zamknięcie okna z komunikatem potwierdzającym
        
        this.addWindowListener(
                new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        final ExitScreen question = new ExitScreen(contr);
                        question.setVisible(true);
                        question.setLocationRelativeTo(null);
                      
                        
                    }
                }
        );
        
    }
    
    
    //tworzymy okienko z jego kolejnymi elementami
    
    private void initComponents() {

        menuBar1 = new java.awt.MenuBar();
        menu1 = new java.awt.Menu();
        menu2 = new java.awt.Menu();
        menuBar2 = new java.awt.MenuBar();
        menu3 = new java.awt.Menu();
        menu4 = new java.awt.Menu();
        menuBar3 = new java.awt.MenuBar();
        menu5 = new java.awt.Menu();
        menu6 = new java.awt.Menu();
        jLabelAddressPort = new JLabel();
        jTextFieldIP = new JTextField();
        jTextFieldPort = new JTextField();
        jLabelSeparator = new JLabel();
        jLabelNick = new JLabel();
        jTextFieldNick = new JTextField();
        jButtonPlay = new JButton();
        jLabelConnectionInfo = new JLabel();
        jMenuBar1 = new JMenuBar();
        jMenuFile = new JMenu();
        jMenuItemExit = new JMenuItem();
        jMenu = new JMenu();
        jMenuItemHelp = new JMenuItem();
        jMenuItemAbout = new JMenuItem();

        menu1.setLabel("File");
        menuBar1.add(menu1);

        menu2.setLabel("Edit");
        menuBar1.add(menu2);

        menu3.setLabel("File");
        menuBar2.add(menu3);

        menu4.setLabel("Edit");
        menuBar2.add(menu4);

        menu5.setLabel("File");
        menuBar3.add(menu5);

        menu6.setLabel("Edit");
        menuBar3.add(menu6);

        setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Badugi - Logowanie");
        setResizable(false);

        jLabelAddressPort.setText("Adres IP serwera i port:");

        jTextFieldIP.setHorizontalAlignment(JTextField.CENTER);
        jTextFieldIP.setText("127.0.0.1");

        jTextFieldPort.setHorizontalAlignment(JTextField.CENTER);
        jTextFieldPort.setText(""+Core_Game_Cfg.DEFAULT_PORT);

        jLabelSeparator.setText(":");

        jLabelNick.setText("Podaj swój nick:");

        //losujemy dwie liczby co z duza szansa da nam wolnego nicka
        
        int first = (int)(Math.random() * 100);
        int second = (int)(Math.random()*100);
        
        int nickaddition = first * second * first * second;      
        
        jTextFieldNick.setHorizontalAlignment(JTextField.CENTER);
        jTextFieldNick.setText("Player"+nickaddition);
        
        //obsługa przyciski "zagraj"
        
        jButtonPlay.setText("ZAGRAJ");
        jButtonPlay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPlayActionPerformed(evt);
            }
        });

        jLabelConnectionInfo.setText("Zagraj z nami w Badugi!");

        //elementy menu pod paskiem tytułu
        
        jMenuFile.setText("Plik");

        jMenuItemExit.setText("Zakończ");
        jMenuItemExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemExitActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuItemExit);

        jMenuBar1.add(jMenuFile);

        jMenu.setText("Pomoc");

        jMenuItemHelp.setText("Help");
        jMenu.add(jMenuItemHelp);

        jMenuItemAbout.setText("About");
        jMenuItemAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemAboutActionPerformed(evt);
            }
        });
        jMenu.add(jMenuItemAbout);

        jMenuBar1.add(jMenu);

        setJMenuBar(jMenuBar1);
        
        //przycisk czyści wpisane domyślnie wartości
        
        JButton btnWyczy = new JButton("Wyczyść");
        btnWyczy.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent arg0) {
        		jTextFieldNick.setText("");
        		jTextFieldPort.setText("");
        		jTextFieldIP.setText("");
        	}
        });
        
        JButton btnDomylne = new JButton("Domyślne");
        btnDomylne.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent arg0) {
        		jTextFieldNick.setText("Player"+nickaddition);
        		jTextFieldPort.setText(""+Core_Game_Cfg.DEFAULT_PORT);
        		jTextFieldIP.setText("127.0.0.1");
        	}
        });

        //parametry wyglądu okna
        
        GroupLayout layout = new GroupLayout(getContentPane());
        layout.setHorizontalGroup(
        	layout.createParallelGroup(Alignment.TRAILING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(layout.createParallelGroup(Alignment.TRAILING)
        				.addComponent(jTextFieldNick, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE)
        				.addGroup(layout.createParallelGroup(Alignment.LEADING)
        					.addGroup(layout.createSequentialGroup()
        						.addComponent(jLabelAddressPort)
        						.addPreferredGap(ComponentPlacement.UNRELATED)
        						.addComponent(jTextFieldIP, GroupLayout.PREFERRED_SIZE, 102, GroupLayout.PREFERRED_SIZE)
        						.addGap(7)
        						.addComponent(jLabelSeparator)
        						.addPreferredGap(ComponentPlacement.RELATED)
        						.addComponent(jTextFieldPort, GroupLayout.PREFERRED_SIZE, 48, GroupLayout.PREFERRED_SIZE))
        					.addComponent(jLabelNick)))
        			.addContainerGap(28, Short.MAX_VALUE))
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap(11, Short.MAX_VALUE)
        			.addGroup(layout.createParallelGroup(Alignment.TRAILING, false)
        				.addGroup(layout.createSequentialGroup()
        					.addComponent(jLabelConnectionInfo)
        					.addGap(89))
        				.addGroup(layout.createSequentialGroup()
        					.addComponent(btnDomylne, GroupLayout.PREFERRED_SIZE, 83, GroupLayout.PREFERRED_SIZE)
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addComponent(btnWyczy, GroupLayout.PREFERRED_SIZE, 83, GroupLayout.PREFERRED_SIZE)
        					.addGap(35)
        					.addComponent(jButtonPlay, GroupLayout.PREFERRED_SIZE, 113, GroupLayout.PREFERRED_SIZE)
        					.addGap(30))))
        );
        layout.setVerticalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(jLabelAddressPort)
        				.addComponent(jTextFieldIP, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(jTextFieldPort, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(jLabelSeparator))
        			.addGap(18)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(jLabelNick)
        				.addComponent(jTextFieldNick, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        			.addGroup(layout.createParallelGroup(Alignment.LEADING)
        				.addGroup(layout.createSequentialGroup()
        					.addGap(18)
        					.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        						.addComponent(btnWyczy, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
        						.addComponent(btnDomylne)))
        				.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addComponent(jButtonPlay, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE)))
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(jLabelConnectionInfo)
        			.addGap(24))
        );
        getContentPane().setLayout(layout);

        pack();
    }

    
     //metoda obslugujaca przycisk "Wyslij"     

    private void jButtonPlayActionPerformed(java.awt.event.ActionEvent evt) {

        int nickLen = jTextFieldNick.getText().length();
        String nick = jTextFieldNick.getText();
        if (Game_Cfg.PLAYER_NAME_LIM[0] > nickLen || nickLen > Game_Cfg.PLAYER_NAME_LIM[1] ) {
            jLabelConnectionInfo.setText( Core_Messages.getMessage(0x02FD) );
            jLabelConnectionInfo.setForeground(Color.red);
            return;
        }
        
    //komunikaty błędu dla niepoprawnych danych

        
        
        if(!validateConnectionData(jTextFieldIP.getText(), jTextFieldPort.getText())){
        	jLabelConnectionInfo.setForeground(Color.red);
        	jLabelConnectionInfo.setText( Core_Messages.getMessage(0x02FE) );
        } else {
        	jLabelConnectionInfo.setForeground(Color.orange);
            jLabelConnectionInfo.setText( Core_Messages.getMessage(0x0200) );
            
            
            try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
            	jLabelConnectionInfo.setForeground(Color.red);
            	jLabelConnectionInfo.setText(Core_Messages.getMessage(0x00FF));
			}
            
            
           
            String ip = jTextFieldIP.getText();
            String port = jTextFieldPort.getText();
            
            
            if(contr.fConnect(ip, Integer.parseInt(port)))
            {

            	if(contr.fSendData(loginDataToJson()))
            	{

            		
            		
                	jLabelConnectionInfo.setForeground(Color.green);
                	jLabelConnectionInfo.setText( Core_Messages.getMessage(0x0101) );
            	

                	Player_Constans.setPlayerNickname( nick );
            		
            		
            		
            	}
    	    	else
    	    	{
    	    		Core_Gui_ErrorWindow.errorWindow(Core_Messages.getMessage(0x02F3), Core_Messages.getMessage(0x0100));
    	    	}
            	
            	
            }
            else
            {
            	jLabelConnectionInfo.setForeground(Color.red);
            	jLabelConnectionInfo.setText(Core_Messages.getMessage(0x02FF) + ip + ":" +  port);
            }
            
            
            //jeśli logowanie udało się, otwieramy okienko z listą stołów
     
            

            
            
        }
        
    }
    //obsługa pozycji "wyjście", "o autorach"
    
    private void jMenuItemExitActionPerformed(java.awt.event.ActionEvent evt) {
    	Controler.guiExScr= new ExitScreen(contr);
    	 
    	//Init
    	Controler.guiExScr.setVisible(true);
    	Controler.guiExScr.setLocationRelativeTo(null);
    }

    
    
  
    
    private void jMenuItemAboutActionPerformed(java.awt.event.ActionEvent evt) {
        final AboutAuthorsScreen about = new AboutAuthorsScreen();
            about.setVisible(true);
            about.setLocationRelativeTo(null);
    }
    
    //przekazanie IP, portu i nazwy uzytkownika
    
    



  

 
    /**
     * 
     * @param textIp
     * @param textPort
     * @return
     */
    
    //sprawdzenie poprawnosci wpisanego adresu IP i portu
    
    private boolean validateConnectionData(String textIp, String textPort) {
    	
    	//TODO: Płynna walidacja PORT_RANGE
    	
        Pattern p = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|[0-9]):([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$");
        Matcher m = p.matcher(textIp + ":" + textPort);
        if (m.matches()) {
            return true;    
        }
        return false;
    }
    
    
    
    
    
    
    
    
    //----------------- [DateMakeForJson] - #START -------------------------
    
    /**
     * Tworzy struktutrę do JSONA
     * 
     * @return
     */
    private Core_JsonDataSchema loginDataToJson()
    {
    	Core_JsonDataSchema data = new Core_JsonDataSchema();
    	
    	//Ustawienie kodu
    	data.setKod(0x01);
    	
    	//Ustawienie argumentów
    	data.setArgs
    	(
    			new int[] {
    					0x01
    			}
    	);
    	
    	
    	//Ustawienie danych
    	data.setDataD1
    	(
    			new Object[] {
    					jTextFieldNick.getText()
    			}
    	);
    	
    	return data;
    	
    }
    
    //----------------- [DateMakeForJson] - #END   -------------------------
    
    
    
    /**
     * Zwraca Kontroler
     * 
     * @return
     */
    public Controler getControler()
    {
    	return contr;
    }
    
    
    
    
}
